using Microsoft.EntityFrameworkCore;
using ProxyServer.EntityFrameworkCore;
using ProxyServer.Quartz;
using ProxyServer.Quartz.Jobs;
using Quartz;
using Quartz.Impl.Matchers;

namespace ProxyServer.Web.Events;

public class PublishedServicesNotification 
{
    public PublishedServicesNotification()
    {
        CreatedTime = DateTimeOffset.UtcNow;
    }

    public DateTimeOffset CreatedTime { get; }
}

public class PublishedServicesNotificationHandler
{
    private readonly ISchedulerFactory _schedulerFactory;
    private readonly ILogger _logger;
    private readonly AppDbContext _appDb;

    public PublishedServicesNotificationHandler(
        ISchedulerFactory schedulerFactory,
        AppDbContext appDb,
        ILogger<PublishedServicesNotificationHandler> logger)
    {
        _schedulerFactory = schedulerFactory;
        _logger = logger;
        _appDb = appDb;
    }

    public async ValueTask Handle(PublishedServicesNotification notification, CancellationToken cancellationToken)
    {
        var schd = await _schedulerFactory.GetScheduler();
        var jobKeys = await schd.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(nameof(CheckServiceCertificateJob)));
        var jobKeysIndex = jobKeys.GroupBy(x => x.Name).ToDictionary(x => Guid.Parse(x.Key), y => y.First());

        var publishedServices = await _appDb.Services.AsNoTracking().ToListAsync(cancellationToken);

        foreach (var service in publishedServices)
        {
            if (jobKeysIndex.ContainsKey(service.Id))
            {
                continue;
            }

            await QuartzHelpers.StartCheckSerivceCertificateOnce(schd, service.Id, cancellationToken);
        }
    }
}